package study.mq.kafka.consumer.listener._2_offset;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * （★）自动提交位移
 * （1）enable-auto-commit=true
 * （2）auto-commit-interval=5000
 */
@Slf4j
@Component
public class _1_CommitListener {

    //@KafkaListener(topics = "topic-1")
    public void onMessage(ConsumerRecord<String, String> record, Consumer consumer) {
        //
        String topic = record.topic();
        int partition = record.partition();
        String key = record.key();
        long offset = record.offset();
        String value = record.value();

        log.info("consumed offset= {}", offset);

        //committed() 方法获取给定分区的上次提交偏移量（无论提交是由这个进程还是另一个进程进行的）
        //此偏移量将在发生故障时用作消费者的位置。此调用将阻止执行远程调用，以从服务器获取最新提交的偏移量
        TopicPartition tp = new TopicPartition(topic, partition);
        Set<TopicPartition> tpSet = CollectionUtil.newHashSet(tp);
        Map<TopicPartition, OffsetAndMetadata> offsetMap = consumer.committed(tpSet);
        offsetMap.forEach((k, v) -> {
            log.info("committed offset: {}", v.offset());
        });
        //position() 方法
        long position = consumer.position(tp);
        log.info("next record position: {}", position);
    }
}
